<?php

class NCore_Page_Auth
{
	private $matchingDirectory = NULL;
	private $settings = array();
	
	function __construct()
	{
		$this->settings['login'] = $_SERVER['SERVER_NAME'].'/login.php';
	}
	
	public function isAuthorized()
	{
		$currentPath = nephtali_remove_base_url_directory($_SERVER['PHP_SELF']);
		
		if(!$this->isProtectedDirectory($currentPath))
			return true;

        // only start session if it was not already started
		if (!isset($_SESSION)) session_start();

        if (is_array($this->settings['required_session_var']))
        {
            foreach ($this->settings['required_session_var'] as $id)
            {
                if(isset($_SESSION[$id]))
                    return true;
            }
        }
        else
        {
            if(isset($_SESSION[$this->settings['required_session_var']]))
                return true;
        }
		
		// if we made it here, not authorized and needs to authenticate for higher privelages
		return false;
	}
	public function isProtectedDirectory($current_dir)
	{
		// check if current directory is protected
		foreach(N::config('protected_directories') as $dir=>$settings)
		{
			if(strpos($current_dir, $dir) === 0)
			{
				$this->matchingDirectory = $dir;
				$this->settings = array_merge($this->settings, $settings);
				return true;
			}
		}
		
		return false;
	}
	public function getLogin()
	{
		return $this->settings['login'];
	}
}

?>